package com.example.zuul.web;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.sun.xml.internal.ws.client.ResponseContext;
import org.apache.tomcat.util.security.MD5Encoder;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.jcajce.provider.digest.MD5;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AccessFilter extends ZuulFilter {
    public String filterType() {
        return "pre"; //前置过滤器
    }

    public int filterOrder() {
        return 0; //优先级，数字越大，优先级越低
    }

    public boolean shouldFilter() {
        return true; //是否执行该过滤器，true代表需要过滤
    }

    public Object run() {
        //  RequestContext 请求上下文   ==> LocalThread
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取请求对象
        HttpServletRequest request = ctx.getRequest();
        //获取传来的参数accessToken  令牌
        Object accessToken = request.getParameter("accessToken");
        if (accessToken == null) {
            System.out.println("access token is empty");
            //过滤该请求，不往下级服务去转发请求，到此结束
            ctx.setSendZuulResponse(false);
            // 设置相应结果码
            ctx.setResponseStatusCode(401);
            // 设置响应结果 json
            ctx.setResponseBody("{\"result\":\"accessToken is empty!\"}");

            // 用 cookie 返回一个令牌
            // 获取浏览器的ip 计算一个令牌
            final String remoteHost = request.getRemoteHost();
            System.out.println(" IP = " + remoteHost);
            final String encode = DigestUtils.md5DigestAsHex(remoteHost.getBytes());
            System.out.println(" encode = " + encode);
            Cookie cookie = new Cookie("accessToken", encode);
            final HttpServletResponse response = ctx.getResponse();
            response.addCookie(cookie);
            return null;
        } else {
            // 重新计算令牌
            final String remoteHost = request.getRemoteHost();
            System.out.println(" IP = " + remoteHost);
            final String encode = DigestUtils.md5DigestAsHex(remoteHost.getBytes());
            System.out.println(" encode = " + encode);
            if ( accessToken.equals(encode) ==  false){
                System.out.println("access token is error");
                //过滤该请求，不往下级服务去转发请求，到此结束
                ctx.setSendZuulResponse(false);
                // 设置相应结果码
                ctx.setResponseStatusCode(401);
                // 设置响应结果 json
                ctx.setResponseBody("{\"result\":\"accessToken is error!\"}");
            }
        }
        //如果有token，则进行路由转发, 这里return的值没有意义，zuul框架没有使用该返回值
        return null;
    }
}